<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Hitelesito
{
	var $CI;
	var $user_table = 'felhasznalo';

	function __construct()
	{
		$this->CI =& get_instance();
	}

	function create($user = '', $password = '', $email = '', $auto_login = true) {
		if($user == '' OR $password == '') {
			return false;
		}
		
		$this->CI->load->modell('felhasznalo_model');
		if ($this->CI->felhasznalo_model->letezik_e($user)) {
			return false;
		} else {
			$password = md5($password);
			
			$user_id = $this->CI->felhasznalo_model->beszur($user, $password, $email);
			if(!$user_id) {
				return false;						
			}

			if($auto_login) {		
				$this->CI->session->sess_destroy();
				$this->CI->session->sess_create();
				$this->CI->session->set_userdata(array(
					'id' => $user_id,
					'azonosito' => $user,
					'belepve' => true,
				));
			}
			return true;
		}
	}
	/*
	function delete($user_id) {
		if(!is_integer($user_id)) {
			return false;			
		}
		$this->CI->load->model('felhasznalo_model');
		return (bool)$this->CI->felhasznalo_model->torol($user_id);
	}
	*/
	function login($user = '', $password = '') {
		if($user == '' OR $password == '') {
			return false;
		}

		if($this->CI->session->userdata('azonosito') == $user) {
			return false;
		}

		$this->CI->load->model('felhasznalo_model');
		$row = $this->CI->felhasznalo_model->felhasznalo($user);

		if (count($row) > 0) {
			if(md5($password) != $row['jelszo']) {
				return false;
			}

			$this->CI->session->sess_destroy();
			$this->CI->session->sess_create();
			unset($row['jelszo']);
			$this->CI->session->set_userdata(array(
				'id' => $row['id'],
				'azonosito' => $user,
				'belepve' => true,
			));			
			return true;
		} else {
			return false;
		}	
	}

	function logout() {
		//Destroy session
		$this->CI->session->sess_destroy();
	}

	public function is_authenticated() {
	    return $this->CI->session->userdata('belepve');
	}
}
?>